package service

import (
	"git.oschina.net/fanbuchi/xgggh/product/database"
	product "git.oschina.net/fanbuchi/xgggh/product/proto/product"
	"errors"
	"git.oschina.net/fanbuchi/xgggh/utils/page"
)

type Products struct {

}

func (super *Products)Create(req *product.Product) error  {
	if req.Id > 0 {
		return errors.New("column Id is not allowed")
	}
	_,err:= database.Master().InsertOne(req)
	return err
}

//Update会自动从user结构体中提取非0和非nil得值作为需要更新的内容
//Cols("Desc") 更新自定字段
// affected, err := engine.Table(new(User)).Id(id).Update(map[string]interface{}{"age":0})
func (super *Products)Update(req *product.Product) error  {
	if req.Id <= 0 {
		err := errors.New("column Id required")
		return err
	}
	affected,err:= database.Master().Id(req.Id).Update(req)
	//affected, err := database.Master().Id(req.Id).
	//	Cols("desc").Cols("price").
	//	Update(req)
	if affected == 0 {
		err := errors.New("0 rows was updated")
		return err
	}
	return err
}

func (super *Products)Delete(req *product.DeleteReq) error  {
	if req.Id <= 0 {
		err := errors.New("column Id required")
		return err
	}
	tmp:=product.Product{Id:req.Id}
	clomns,err:= database.Master().Delete(&tmp)
	if clomns == 0 {
		err := errors.New("0 rows was deleted")
		return err
	}
	return err
}

func (super *Products)Query(req *product.QueryReq) ( *product.Product, error)  {
	if req.Id <= 0 {
		err := errors.New("column Id required")
		return nil,err
	}

	var tmp product.Product
	_,err:= database.Master().ID(req.Id).Unscoped().Get(&tmp)
	return &tmp,err
}


func (super *Products)QueryList(req *product.QueryListReq) ( []*product.Product, error)  {
	if len(req.Id) == 0  {
		err := errors.New("column Id required")
		return nil,err
	}
	//直接数组转slice
	//slice := req.Id[:]
	var tmp []*product.Product
	err:= database.Master().In("id",req.Id).Unscoped().Find(&tmp)
	return tmp,err
}

func (super *Products)Search(req *product.SearchReq) ([]*product.Product,error)  {
	limit,offset:=page.Page(req.PageNumber,req.ResultPerPage)
	params:=req.Params
	if params==nil {
		params=&product.Product{}
	}
	var tmp []*product.Product;
	err:= database.Master().Limit(limit,offset).Find(&tmp,params)
	return tmp,err
}
